<template>
  <div class="container">
    <div class="list">
      <div class="search-container">
        <input
          type="text"
          placeholder="请输入城市名称"
          class="search-input"
          v-model="searchCity"
        />
        <ul class="search-results" v-show="showResults">
          <p class="error-message" v-show="isNetworkError">
            对不起网络似乎除了点问题 请稍后再查询
          </p>
          <p class="no-results" v-show="!hasCityResults && !isNetworkError">
            似乎没有找到你查找的城市
          </p>
          <li
            v-for="(item, index) in cityList"
            :key="index"
            @click="goToWeatherDetail(item)"
          >
            {{ item.cityName }}
          </li>
        </ul>
      </div>
      <h2 class="empty-message" v-show="savedCities.length === 0">
        暂时没有保存过城市天气信息，请查询后点击右上角"+"号保存。
      </h2>
      <div class="cities-scroll-container" v-show="savedCities.length > 0">
        <div class="city-item" v-for="city in savedCities" :key="city.adcode">
          <div
            class="city-info"
            @mouseenter="hoverAdcode = city.adcode"
            @mouseleave="hoverAdcode = ''"
          >
            <h3>{{ city.name }}</h3>
            <span>{{ city.temp }}度</span>
          </div>
          <div class="city-actions" v-show="hoverAdcode === city.adcode">
            <button class="view-btn" @click="goToWeatherDetail(city)">
              查看
            </button>
            <button class="delete-btn" @click="removeSavedCity(city.adcode)">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>
    <h2>近期天气</h2>
    <div class="weather-container">
      <div class="weather-content">
        <div class="weather-days">
          <div class="weather-day" v-for="day in recentWeather" :key="day.date">
            <span>{{ day.week }}</span>
            <span>{{ day.date }}</span>
            <span>{{ day.weather }}</span>
            <span>{{ day.wind }}</span>
          </div>
        </div>
        <div class="weather-chart">
          <v-chart :option="option"></v-chart>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getIpData, getCityData, getWeatherPredictionData } from '@/api'
const router = useRouter()

const searchCity = ref('')
const cityList = ref([])
const showResults = ref(false)
const isNetworkError = ref(false)

const hasCityResults = computed(() => cityList.value.length > 0)

const savedCities = ref([])
const hoverAdcode = ref('')

const recentWeather = ref([])
const dayTemps = ref([])
const nightTemps = ref([])
const option = ref({})

const key = ref('e05b2f8dddd45367d027e8f1792cc710')

let timer = null
watch(
  () => searchCity.value,
  (newVal) => {
    // 清除上次计时器
    if (timer) {
      clearTimeout(timer)
    }
    // 检测空值
    if (!newVal) {
      cityList.value = []
      showResults.value = false
      return
    }
    // 延迟搜索减少无效请求
    timer = setTimeout(async () => {
      showResults.value = true
      isNetworkError.value = false
      try {
        const res = await getCityData(newVal, key.value)
        const fields = ['district', 'city', 'province']
        cityList.value = res.geocodes.map((item) => {
          const validField = fields.find(
            (field) => typeof item[field] === 'string' && item[field].trim()
          )
          return {
            cityName: item[validField],
            adcode: item.adcode,
          }
        })
      } catch (err) {
        isNetworkError.value = true
        cityList.value = []
      }
    }, 300)
  }
)

// 转跳到天气详情页面
const goToWeatherDetail = (city) => {
  router.push({
    path: `/weather/${city.adcode}`,
    query: { search: city.name || city.cityName, adcode: city.adcode },
  })
  showResults.value = false
  searchCity.value = ''
}

// 从本地获取已保存的城市
const getSavedCities = () => {
  const saved = localStorage.getItem('savedWeatherCities')
  savedCities.value = saved ? JSON.parse(saved) : []
}

// 删除已保存的城市
const removeSavedCity = (adcode) => {
  savedCities.value = savedCities.value.filter((city) => city.adcode !== adcode)
  localStorage.setItem('savedWeatherCities', JSON.stringify(savedCities.value))
}

// 初始化星期
const initWeek = (weekNum) => {
  const week = {
    1: '周一',
    2: '周二',
    3: '周三',
    4: '周四',
    5: '周五',
    6: '周六',
    7: '周日',
  }
  return week[weekNum]
}

// 初始化天气数据
const initRecentWeather = async () => {
  const ipData = await getIpData(key.value)
  const forecastsData = await getWeatherPredictionData(ipData.adcode, key.value)
  const forecasts = forecastsData.forecasts[0].casts

  // 获得天气数据
  recentWeather.value = forecasts.map((item, index) => {
    const week =
      index === 0 ? '今天' : index === 1 ? '明天' : initWeek(item.week)
    dayTemps.value.push(item.daytemp)
    nightTemps.value.push(item.nighttemp)
    return {
      week,
      date: item.date.slice(5),
      weather: item.dayweather,
      wind: item.daypower,
    }
  })
  renderChart()
}

const renderChart = () => {
  option.value = {
    xAxis: {
      type: 'category',
      show: false,
      boundaryGap: false,
    },
    yAxis: {
      type: 'value',
      show: false,
      axisLabel: {
        formatter: '{value} °C',
      },
      scale: true,
    },
    grid: {
      top: '20%',
      left: '7%',
      right: '10%',
      bottom: '20%',
      containLabel: true,
    },
    series: [
      {
        name: '白天气温',
        type: 'line',
        data: dayTemps.value,
        smooth: true,
        label: {
          show: true,
          formatter: function (params) {
            return `白${params.value}℃`
          },
          position: 'top',
          fontSize: 10,
          color: 'white',
        },
      },
      {
        name: '夜晚气温',
        type: 'line',
        data: nightTemps.value,
        smooth: true,
        label: {
          show: true,
          formatter: function (params) {
            return `晚${params.value}℃`
          },
          position: 'bottom',
          fontSize: 10,
          color: 'white',
        },
      },
    ],
  }
}

onMounted(() => {
  getSavedCities()
  initRecentWeather()
})
</script>

<style lang="scss" scoped>
.container {
  padding: 0 160px;
  margin: 0 70px;
  color: white;

  .list {
    display: flex;
    flex-direction: column;

    .search-container {
      position: relative;
      margin-bottom: 32px;
      padding-top: 16px;

      .search-input {
        padding: 8px 4px;
        width: 100%;
        background: transparent;
        border: none;
        border-bottom: 1px solid white;
        outline: none;
        color: white;
        font-size: 16px;
        transition: all 0.2s;

        &:focus {
          border-bottom: none;
          box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1),
            0 4px 6px -4px rgb(0 0 0 / 0.1);
        }

        &::placeholder {
          color: white;
        }
      }

      .search-results {
        position: absolute;
        background: rgb(0, 78, 113);
        color: white;
        width: 100%;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        padding: 8px 4px;
        top: 62px;
        z-index: 10;

        li {
          padding: 8px 12px;
          cursor: pointer;
          transition: all 0.3s ease;
          list-style: none;

          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }
        }

        .error-message,
        .no-results {
          display: none;
          padding: 8px 12px;
        }
      }
    }

    .empty-message {
      text-align: center;
      color: white;
      transition: opacity 0.2s;
      font-size: 16px;
      font-weight: 400;
      margin-top: 15px;
    }

    .cities-scroll-container {
      max-height: 300px;
      overflow-y: auto;

      .city-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
        width: 100%;
        position: relative;
        transition: all 1s ease;

        &:hover .city-actions {
          display: flex !important;
        }

        .city-info {
          background: rgb(0, 78, 113);
          color: white;
          padding: 8px 16px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          cursor: pointer;
          width: 100%;
          transition: all 0.3s ease;

          &:hover {
            background: rgba(0, 78, 113, 0.9);
          }

          h3 {
            font-weight: 500;
            margin: 0;
          }

          span {
            font-weight: 600;
          }
        }

        .city-actions {
          gap: 8px;
          margin-left: 16px;
          white-space: nowrap;

          &.visible {
            display: flex !important;
          }

          .view-btn,
          .delete-btn {
            background: #eab308;
            color: white;
            text-align: center;
            width: 80px;
            padding: 8px;
            transition: background-color 0.2s;
            font-weight: 500;
            border: none;
            cursor: pointer;

            &:hover {
              background: #ca8a04;
            }

            &:active {
              transform: scale(0.95);
            }
          }
        }
      }
    }
  }

  h2 {
    font-size: 16px;
    font-weight: 500;
    margin-top: 24px;
  }

  .weather-container {
    background: rgb(0, 78, 113);
    padding: 0 48px;
    padding-top: 40px;
    margin-top: 8px;
    border-radius: 4px;

    .weather-content {
      .weather-days {
        display: flex;
        gap: 24px;

        .weather-day {
          display: flex;
          flex-direction: column;
          flex: 1;
          text-align: center;
          gap: 16px;

          span {
            display: block;
          }
        }
      }

      .weather-chart {
        height: 160px;
        margin-top: 20px;
      }
    }
  }
}
</style>
